#coding:utf-8

from elasticsearch import Elasticsearch

import datetime
import json

class EsStore(object):

    def __init__(self, o, p, e, t):
        self.es = Elasticsearch(hosts=[{'host':o,'port':p}])
        self.index = e
        self.type = t

    def getByTime(self, st, et, fields='*'):
        T1 = st.strftime('%Y-%m-%d %H:%M:%S')
        T2 = et.strftime('%Y-%m-%d %H:%M:%S')
        q = {'range':{
            'create_time':{
                "from": T1,
                "to": T2
            }
        }}

        q = {"query":{
            "bool": {
                "must":[q]
            }
        }}        

        res = self.es.search(index=self.index,doc_type=self.type,\
                                body=q,scroll='10m',search_type='scan',\
                                _source_include=fields,size=500)
        si = res['_scroll_id']
        ct = res['hits']['total']
        return {'si':si,'ct':ct}

    def next(self,si):
        res = self.es.scroll(scroll_id=si,scroll='10m')
        si = res['_scroll_id']
        res = res['hits']['hits']
        res = [r['_source'] for r in res]
        return {'si':si,'rs':res}  